<?php
/**
 * Created by PhpStorm.
 * User: 程阳
 * Date: 2017/3/1
 * Time: 21:50
 */

namespace Home\Controller;

use Common\Controller\HomeController;
use Org\Util\Cart;

class CartController extends HomeController
{
    public function index(){
//        dd($_SESSION);
        if(isset($_SESSION['cart'])){
            $cartData = $_SESSION['cart'];
            foreach($cartData['goods'] as $k => $v){
                $cartData['goods'][$k]['good'] = M("Goods")->where("gid = {$v['id']}")->find();
                $cartData['goods'][$k]['info'] = $v['name'];
                foreach($v['options'] as $kk => $vv){
                    $cartData['goods'][$k]['info'] .= $vv;
                }
            }
            if($cartData){
//                dd($cartData);
                $this->assign('cartData',$cartData);
            }
        }

        $this->display();
    }

    public function changeNums(){
        if(IS_AJAX){
            $goodKey = I("post.goodKey");
            $num = I("post.num");
            // session('user.user_id',10);  //设置session
            $data=array(
                'sid'=>$goodKey,// 唯一 sid，添加购物车时自动生成
                'num'=>$num,
            );
            (new Cart())->update($data);
        }
        $this->ajaxReturn(["total"=>$_SESSION['cart']['total'],"goodData"=>$_SESSION['cart']['goods'][$goodKey]]);
    }

    public function delCart(){
        if(IS_AJAX){
            $goodKey = I("post.goodKey");
            $goodTotal = I("post.goodTotal");
            $goodNum = I("post.goodNum");
            unset($_SESSION['cart']['goods'][$goodKey]);
            $_SESSION['cart']['total'] -= $goodTotal;
            $_SESSION['cart']['total_rows'] -= $goodNum;
            if(!$_SESSION['cart']['goods']){
                $_SESSION['cart'] = NULL;
            }
            $this->ajaxReturn(['total'=>$_SESSION['cart']['total'],'len'=>count($_SESSION['cart']['goods'])]);
        }

    }
}